import logging
import os
from logging.handlers import RotatingFileHandler
from datetime import datetime

class Logger:
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(Logger, cls).__new__(cls)
            cls._instance._initialize_logger()
        return cls._instance
    
    def _initialize_logger(self):
        """初始化日志配置"""
        self.logger = logging.getLogger('algo_trading')
        self.logger.setLevel(logging.DEBUG)
        
        # 创建日志目录
        log_dir = 'logs'
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
            
        # 生成日志文件名（按日期）
        log_file = os.path.join(log_dir, f'algo_trading_{datetime.now().strftime("%Y%m%d")}.log')
        
        # 文件处理器（支持日志文件轮转，最大10MB，保留5个备份）
        file_handler = RotatingFileHandler(
            log_file,
            maxBytes=10*1024*1024,  # 10MB
            backupCount=5,
            encoding='utf-8'
        )
        file_handler.setLevel(logging.DEBUG)
        
        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        
        # 设置日志格式
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)
        
        # 添加处理器
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)
    
    def debug(self, message, exc_info=False):
        """记录调试级别日志"""
        self.logger.debug(message, exc_info=exc_info)
    
    def info(self, message, exc_info=False):
        """记录信息级别日志"""
        self.logger.info(message, exc_info=exc_info)
    
    def warning(self, message, exc_info=False):
        """记录警告级别日志"""
        self.logger.warning(message, exc_info=exc_info)
    
    def error(self, message, exc_info=False):
        """记录错误级别日志"""
        self.logger.error(message, exc_info=exc_info)
    
    def critical(self, message, exc_info=False):
        """记录严重错误级别日志"""
        self.logger.critical(message, exc_info=exc_info)

# 创建全局日志实例
logger = Logger() 